package video.dali.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import video.dali.common.Result;
import video.dali.common.utils.JwtUtil;

@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {



        //是否是登陆操作
        String url = request.getRequestURL().toString();
        log.info(request.getRequestURI());
        log.info("开始校验");
        log.info("过滤的网址是:{}",url);

        if (url.contains("login")) {
            log.info("此为登陆操作，放行");
            return true;
        }
        if (url.contains("static")) {
            log.info("此为访问静态资源操作，放行");
            return true;
        }
        //是否有jwt
        String jwt = request.getHeader("authorization");
        if (!StringUtils.hasLength(jwt)){
            log.info("token中没有jwt,返回登录页面");
            Result error = Result.error("NOT_LOGIN");
            String errorJson = JSONObject.toJSONString(error);
            response.getWriter().write(errorJson);
            return false;
        }

        //jwt解析
        try {
            JwtUtil.parseJwt(jwt);
        } catch (Exception e) {
            log.info("jwt解析失败");
            Result error = Result.error("NOT_LOGIN");
            String errorJson = JSONObject.toJSONString(error);
            response.getWriter().write(errorJson);
            return false;
        }
        //放行
        log.info("校验通过，放行");
        return true;

    }

}
